package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BaseDao {
	private String driver = "com.mysql.jdbc.Driver";							//数据库驱动字符串
	private String url = "jdbc:mysql://localhost:3306/mogujie";		//连接URL字符串
	private String user = "root";															//数据库用户名
	private String password = "root";													//用户密码
	Connection conn=null;																	//数据连接对象
	/*
	 * 获取数据库连接对象
	 */
	public Connection getConnection() {
		if (conn == null) {
			//获取连接并捕获异常
			try {
				Class.forName(driver);
				conn = DriverManager.getConnection(url,user,password);
			} catch (Exception e) {				
				// TODO Auto-generated catch block
				e.printStackTrace();				//异常处理
			}
		}
		return conn;				//返回连接对象
	}
	/**
	 * 关闭数据库连接
	 * @param conn数据库连接
	 * @param stmt Statement对象
	 * @param rs 结果集
	 */
	public void closeAll(Connection conn,Statement stmt,ResultSet rs) {
		//诺结果集对象不为空,则关闭
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//诺Statement对象不为空,则关闭
		try {
			if (stmt != null) {
				stmt.close();
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		//诺数据库连接对象不为空,则关闭
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	/**
	 * 增,删,改的操作
	 * @param preparedSql 预编译的SQL语句
	 * @param param参数的字符串数组
	 * @return 影响的行数
	 */
	public int exceuteUpdate (String preparedSql,Object [] param) {
		PreparedStatement pstmt = null;
		int num = 0;
		conn = getConnection();
		try {
			pstmt = conn.prepareStatement(preparedSql);
			if (pstmt != null) {
				for(int i= 0; i < param.length; i++) {
					//为预编译sql设置参数
					pstmt.setObject(i+1, param[i]);
				}
			}
			System.out.println(pstmt);
			num = pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//closeAll(conn, pstmt, null);
		}
		return num;
	}

	/**u
	 * 查询
	 * @param preparedSql
	 * @param param
	 * @return 结果集
	 */
	public ResultSet execute(String preparedSql,Object [] param) {
		ResultSet rs = null;
		conn = getConnection();
		PreparedStatement pstmt = null;
		try {
			pstmt = conn.prepareStatement(preparedSql);
			if (pstmt != null) {
				for(int i =0; i< param.length; i++) {
					pstmt.setObject(i+1, param[i]);
				}
			}
			System.out.println(pstmt);
			rs = pstmt.executeQuery();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
}
